package com.wwlwxg.forkjoin;

import org.junit.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class TestForkjoinStream {

    private final Long num = 10_0000_0000L;

    @Test
    public void testSum() {
        Long sum = 0L;
        long start = System.currentTimeMillis();
        for(Long i = 0L; i <= num; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("sum = " + sum + ", 时间： " + (end - start));      // 8083
    }

    @Test
    public void testforkjoin() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        ForkJoinTask<Long> demo = new ForkjoinDemo(0L, num);

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task = pool.submit(demo);

        Long sum = task.get();

        System.out.println("sum = " + sum + ", 时间：" + (System.currentTimeMillis() - start));   // 5026

    }

    @Test
    public void testStream() {
        long start = System.currentTimeMillis();

        long sum = LongStream.rangeClosed(0, num).parallel().reduce(0, Long::sum);      // 269
        System.out.println("sum = " + sum + ", 时间：" + (System.currentTimeMillis() - start));

    }
}
